#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "socketmanager.h" // 包含 SocketManager 类的头文件
#include <QMessageBox>

registerdialog::registerdialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::registerdialog),
    socketManager(new SocketManager(this)) // 初始化 SocketManager 对象
{
    ui->setupUi(this);
    // 连接信号与槽
    connect(socketManager, &SocketManager::connectionFailed, this, &registerdialog::onConnectionFailed);
    connect(socketManager, &SocketManager::dataReceived, this, &registerdialog::onDataReceived);

    // 加载并信任 CA 证书
    socketManager->loadCaCertificate("F:/Desktop/lib/ca.crt");
}

registerdialog::~registerdialog()
{
    delete ui;
}

void registerdialog::on_btn_submit_clicked()
{
    QString username = ui->Reg_username->text();
    QString password = ui->Reg_pwd->text();
    QString confirmPassword = ui->Reg_re_pwd->text();
    if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
        QMessageBox::warning(this, "错误", "所有字段均为必填!");
        return;
    }
    if (password != confirmPassword) {
        QMessageBox::warning(this, "错误", "两次密码不一致!");
        return;
    }
    QByteArray dataToSend = (username + " " + password).toUtf8();
    socketManager->connectToServer("111.231.80.52", 8935); // 连接到服务器
    socketManager->sendData(dataToSend); // 使用 SocketManager 发送数据
}

void registerdialog::on_btn_clear_clicked()
{
    ui->Reg_username->clear();
    ui->Reg_pwd->clear();
    ui->Reg_re_pwd->clear();
}

void registerdialog::on_btn_back_clicked()
{
    this->close();
}

void registerdialog::onConnectionFailed(const QString &errorMessage)
{
    QMessageBox::information(this, "", errorMessage);
}

void registerdialog::onDataReceived(const QByteArray &data)
{
    QString response = QString::fromUtf8(data);
    if (response == "注册成功") {
        QMessageBox::information(this, "", response);
        this->accept();
    } else {
        QMessageBox::warning(this, "", response);
    }
}
